package com.dinphin.site.novel.service.serviceImpl;

import com.dinphin.site.novel.entity.Book;
import com.dinphin.site.novel.entity.BookLinkType;
import com.dinphin.site.novel.repository.BookLinkTypeRepository;
import com.dinphin.site.novel.repository.BookRepository;
import com.dinphin.site.novel.service.BookLinkTypeService;
import com.dinphin.site.novel.util.Result;
import com.dinphin.site.novel.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Desc:
 * <p>
 * <p>
 * Created by dd on 2018/9/5 16:33
 */

@Service
public class BookLinkTypeServiceImpl  implements BookLinkTypeService {

    @Autowired
    private BookLinkTypeRepository bookLinkTypeRepository;
    @Autowired
    private BookRepository bookRepository;

    public boolean addBookLinkType(long bookId, int[] types) {
        long n = bookLinkTypeRepository.count();
        BookLinkType bookLinkType = new BookLinkType();
        bookLinkType.setBookId(bookId);
        for (int i = 0; i < types.length; i++) {
            bookLinkType.setTypeId(types[i]);
            bookLinkTypeRepository.save(bookLinkType);
        }
        if (bookLinkTypeRepository.count() == (n + types.length)) return true;
        else return false;
    }

    public boolean updateBookLinkType(long bookId, int[] types) {
        long n = bookLinkTypeRepository.count();
        bookLinkTypeRepository.deleteByBookId(bookId);
        if (bookLinkTypeRepository.count() == (n - types.length))
            return this.addBookLinkType(bookId, types);
        else return false;
    }


    public Result findBooksByTypes(List<Long> types) {
        List<BookLinkType> bookLinkTypes = bookLinkTypeRepository.findBookLinkTypesByTypeId(types.get(0));
        for (int i = 1; i < types.size(); i++) {
            for (int j = 0; j < bookLinkTypes.size(); j++) {
                if (bookLinkTypes.get(j).getTypeId() != types.get(i))
                    bookLinkTypes.remove(j);
            }
        }
        List<Book> books = new ArrayList<>();
        for (int i = 0; i < bookLinkTypes.size(); i++) {
            books.add(bookRepository.findById(bookLinkTypes.get(i).getBookId()).get());
        }
        return new Result(ResultCode.SUCCESS, books);
    }
}
